global Queryed := ""
global Running := false

CHKQUERY(){
    if Running
    {
        WriteLog("A task is running, wait for next chance`n")
        return
    }
    Running := true
    GuiControlGet, EditContents
    EditContents := Trim(EditContents)
    StringLower, EditContents, EditContents

    if(StrLen(EditContents) == 0){
        LV_Delete()
        Queryed := EditContents
    }
    else if( EditContents <> Queryed )
    {
        Queryed := EditContents

        EditContents := StrReplace(EditContents, A_Space, ".*")
        RegExp := ".*" . EditContents . ".*"

        ; WriteLog("Query target is " . EditContents . "`n")

        LV_Delete()
        count := 1
        For index, element in Total
        {
            Name := element.Name
            Type := element.Type
            StringLower, LowerName, Name

            if( 0 <> RegExMatch(LowerName, RegExp)){
                Select := ""
                if( count = 1 ){
                    Select := "Select"
                }
                LV_Add(Select, count,  Name, "[" . Type . "]=>" . Name, Jxon_Dump(element))
                count := count + 1
            }
        }
    }
    Running := false
}

#IfWinNotExist ahk_class AutoHotkeyGUI
!Esc::
Gui,+AlwaysOnTop -SysMenu + Owner
Gui Font, s12, Arial
Gui Add, ComboBox, x50 y25 w500 h25 vEditContents
Gui Add, ListView, x50 y75 w500 h320 Grid Count, Idx | Command | Comment | Target
LV_ModifyCol(1, 30)
LV_ModifyCol(2, 200)
LV_ModifyCol(3, 250)
LV_ModifyCol(4, 0)

Gui Show, w600 h420 Center, AlwaysOnTop Window
OnMessage(0x0100, "WM_KEYDOWN")
Queryed := ""
SetTimer, CHKQUERY, 100
return
#IfWinNotExist


#IfWinExist ahk_class AutoHotkeyGUI
!Esc::
WinActivate, ahk_class AutoHotkeyGUI
return
#IfWinNotExist


WM_KEYDOWN(wParam, lParam){
    keycode := 0
    if(wParam = 40 or wParam = 38)
    {
        if(lParam != 0 ){
            GuiControlGet, Focused, Focus
            if(Focused <> "SysListView321"){
                keycode := wParam
            }
        }
    }
    if(wParam = 39)
    {
        keycode := 40
    }
    else if(wParam = 37){
        keycode := 38
    }
    if(keycode > 0){
        PostMessage,0x0100, %wParam%, 0,SysListView321,ahk_class AutoHotkeyGUI
        row := LV_GetNext(0, "F")
        if(row = 0){
            PostMessage,0x0100, %wParam%, 0,SysListView321,ahk_class AutoHotkeyGUI
            WriteLog("double`n")
        }
    }

}

#IfWinActive ahk_class AutoHotkeyGUI
Enter::
  Gui, Submit, NoHide
  TotalCount := LV_GetCount()

  if not TotalCount
  {
      Return
  }

  RowNumber := 0
  RowNumber := LV_GetNext(RowNumber)

  if not RowNumber
  {
      RowNumber := 1
  }
  LV_GetText(Text, RowNumber, 4)
  WriteLog(Text)
  Selected := Jxon_Load(Text)

  Queryed := ""
  SetTimer, CHKQUERY, Delete
  Gui, Destroy

  RunElement(Selected)

  Return
#IfWinActive

GuiEscape:
GuiClose:
Queryed := ""
SetTimer, CHKQUERY, Delete
Gui, Destroy
return
